<template>
  <div class="send-display-container">
    <div class="filter-container">
      <div class="label">字典名称：</div>
      <div class="input-container">
        <a-input v-model="queryFrom.dictName" />
      </div>
      <div class="label">字典编码：</div>
      <div class="input-container">
        <a-input v-model="queryFrom.dictCode" />
      </div>
      <a-button type="primary" class="btn" @click="initList">查询</a-button>
      <a-button class="btn" @click="resetForm">重置</a-button>
    </div>
    <div class="filter-container">
      <a-button type="primary" class="btn" @click="showModal">新建</a-button>
      <a-modal
        width="40%"
        :title="title"
        :visible="addVisible"
        @ok="handleOk"
        @cancel="handleCancel"
      >
        <div style="margin-top: 24px">
          <a-form-model
            ref="ruleAddForm"
            :model="addForm"
            :rules="addRules"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
          >
            <a-row>
              <a-col :span="24">
                <a-form-model-item ref="dictName" label="字典名称" prop="dictName">
                  <a-input
                    v-model="addForm.dictName"
                    @blur="() => { $refs.dictName.onFieldBlur() }"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item ref="dictCode" label="字典编码" prop="dictCode">
                  <a-input
                    :disabled="true"
                    v-model="addForm.dictCode"
                    @blur="() => { $refs.dictCode.onFieldBlur() }"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item ref="bz" label="备注" prop="bz">
                  <a-input :rows="4" v-model="addForm.bz" type="textarea"></a-input>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
        </div>
      </a-modal>
    </div>
    <div>
      <a-table
        :loading="loading"
        :columns="columns"
        :data-source="data"
        bordered
        :pagination="pagination"
        :rowKey="(record,index)=>{return index}">
        <a slot="b" slot-scope="text" href="https://www.google.com">{{ text }}</a>
        <span slot="action" slot-scope="text, record">
          <a href="javascript:" @click="updateShowModal( text, record )">编辑</a>
          <a-divider type="vertical" />
          <a href="javascript:" @click="onAuthorization( text, record )">字典配置</a>
          <a-divider type="vertical" />
          <a-popconfirm
            title="是否删除？"
            ok-text="是"
            cancel-text="否"
            @confirm="confirmDel( text, record )"
            @cancel="cancelDel"
          >
            <a href="#">删除</a>
          </a-popconfirm>
        </span>
      </a-table>
    </div>
    <a-back-top />
    <a-drawer
      title="字典列表"
      width="35%"
      :visible="visible"
      :body-style="{ paddingBottom: '80px' }"
      @close="onClose"
    >
      <div class="drawer-send-display-container">
        <div class="drawer-filter-container">
          <div class="label">名称：</div>
          <div class="input-container">
            <a-input v-model="queryZdFrom.spName" />
          </div>
          <div class="label">状态：</div>
          <div class="input-container">
            <a-select
              :value="queryZdFrom.spState"
              default-value="null"
              style="width: 100%"
              @change="handleChangeGender"
              placeholder="请选择">
              <a-select-option value="null">
                全部
              </a-select-option>
              <a-select-option value="1">
                有效
              </a-select-option>
              <a-select-option value="0">
                无效
              </a-select-option>
            </a-select>
          </div>
          <a-button type="primary" class="btn" @click="onZdQuery">查询</a-button>
          <a-button class="btn" @click="resetZdForm">重置</a-button>
        </div>
      </div>
      <div class="send-display-container">
        <a-button type="primary" class="btn" @click="zdShowModal">新建</a-button>
        <a-modal
          width="40%"
          :title="title"
          :visible="zdVisible"
          :confirm-loading="confirmLoading"
          @ok="handleZdOk"
          @cancel="handleZdCancel"
        >
          <div style="margin-top: 24px">
            <a-form-model
              ref="ruleZdForm"
              :model="zdForm"
              :rules="zdRules"
              :label-col="labelCol"
              :wrapper-col="wrapperCol"
            >
              <a-row>
                <a-col :span="24">
                  <a-form-model-item ref="spName" label="名称" prop="spName">
                    <a-input
                      v-model="zdForm.spName"
                      @blur="() => { $refs.spName.onFieldBlur() }"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="24">
                  <a-form-model-item ref="spValue" label="数据值" prop="spValue">
                    <a-input
                      v-model="zdForm.spValue"
                      @blur="() => { $refs.spValue.onFieldBlur() }"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="24">
                  <a-form-model-item ref="spRemark" label="描述" prop="spRemark">
                    <a-input v-model="zdForm.spRemark"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="24">
                  <a-form-model-item ref="spWeight" label="排序" prop="spWeight">
                    <a-input-number id="inputNumber" v-model="zdForm.spWeight" :min="1" :max="1000" />
                  </a-form-model-item>
                </a-col>
                <a-col :span="24">
                  <a-form-model-item ref="spState" label="是否启用" prop="spState">
                    <a-switch v-model="zdForm.spState" checked-children="启用" un-checked-children="禁用" default-checked />
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-form-model>
          </div>
        </a-modal>
      </div>
      <a-table
        :loading="zdLoading"
        :columns="zdColumns"
        :data-source="zdData"
        bordered
        @change="onChangeZd"
        :pagination="zdPagination"
        :rowKey="(record,index)=>{return index}">
        <span slot="action" slot-scope="text, record">
          <a href="javascript:" @click="updateZdShowModal( text, record )">编辑</a>
          <a-divider type="vertical" />
          <a-popconfirm
            title="是否删除？"
            ok-text="是"
            cancel-text="否"
            @confirm="confirmZdDel( text, record )"
            @cancel="cancelDel"
          >
            <a href="#">删除</a>
          </a-popconfirm>
        </span>
      </a-table>
    </a-drawer>
  </div>
</template>

<script>
import {
  selectSysDictList,
  saveDictInfo,
  updateSysDict,
  getDictMaxCode,
  deleteSysDict,
  selectSysDictParamList,
  saveDictParamInfo,
  updateSysDictParam,
  deleteSysDictParam
} from '@/api/dict'

const columns = [
  {
    title: '字典名称',
    dataIndex: 'dictName',
    key: 'dictName',
    align: 'center',
    width: '20%'
  },
  {
    title: '字典编号',
    dataIndex: 'dictCode',
    key: 'dictCode',
    align: 'center',
    width: '20%'
  },
  {
    title: '描述',
    dataIndex: 'bz',
    key: 'bz',
    align: 'center',
    width: '40%'
  },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    scopedSlots: { customRender: 'action' },
    width: '20%'
  }

]

const zdColumns = [
  {
    title: '名称',
    dataIndex: 'spName',
    key: 'spName',
    align: 'center',
    width: '20%'
  },
  {
    title: '数据值',
    dataIndex: 'spValue',
    key: 'spValue',
    align: 'center',
    width: '20%'
  },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    scopedSlots: { customRender: 'action' },
    width: '20%'
  }

]

export default {
  name: 'Dict',
  data () {
    return {
      data: [],
      zdData: [],
      columns,
      zdColumns,
      addForm: {
        dictId: '',
        dictName: '',
        dictCode: '',
        bz: ''
      },
      zdForm: {
        spValue: '',
        spType: '',
        spName: '',
        spState: true,
        spWeight: '',
        spRemark: ''
      },
      replaceFields: {
        children: 'children',
        title: 'menuName',
        value: 'menuId',
        key: 'menuId'
      },
      addRules: {
        dictName: [
          { required: true, message: '请输入字典名称!', trigger: 'blur' }
        ],
        dictCode: [
          { required: true, message: '请输入字典编码!', trigger: 'blur' }
        ]
      },
      zdRules: {
        spName: [
          { required: true, message: '请输入参数名称!', trigger: 'blur' }
        ],
        spValue: [
          { required: true, message: '请输入参数编码!', trigger: 'blur' }
        ],
        spState: [
          { required: true, message: '请选择是否启用!', trigger: 'blur' }
        ]
      },
      autoExpandParent: true,
      selectedKeys: [],
      expandedKeysss: [],
      allTreeKeys: [],
      defaultExpandAll: true,
      loading: false,
      zdLoading: false,
      visible: false,
      addVisible: false,
      zdVisible: false,
      confirmLoading: false,
      wrapperCol: { span: 14 },
      labelCol: { span: 4 },
      title: '',
      queryFrom: {
        dictName: '',
        dictCode: ''
      },
      queryZdFrom: {
        spType: '',
        spName: '',
        spState: 'null'
      },
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: (total, range) => `显示第${range[0]}至${range[1]}项结果，共${total}项`
      },
      zdPagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: (total, range) => `显示第${range[0]}至${range[1]}项结果，共${total}项`
      },
      treeData: [],
      menuIds: [],
      checkStrictly: true,
      menuIdsString: '',
      checkedKeys: []
    }
  },
  created () {
    this.initList()
  },
  methods: {
    initList () {
      this.pagination.current = 1
      this.onQuery()
    },
    forEachChild (check, data) {
      data.forEach(x => {
        check.push(x.menuId)
        if (x.children !== null && x.children !== undefined && x.children.length > 0) {
          this.forEachChild(check, x.children)
        }
      })
    },
    onAuthorizationSet (checkedKeys) {
      if (this.checkStrictly) {
        this.menuIds = checkedKeys.checked
      } else {
        this.menuIds = checkedKeys
      }
      console.log(this.menuIds)
      if (this.menuIds.length > 0) {
        this.menuIdsString = this.menuIds.toLocaleString()
      }
    },
    onAuthorization (text, record) {
      this.visible = true
      this.queryZdFrom.spType = record.dictCode
      this.onZdQuery()
    },
    onQuery () {
      this.loading = true
      const params = {
        dictName: this.queryFrom.dictName === '' ? null : this.queryFrom.dictName,
        dictCode: this.queryFrom.dictCode === '' ? null : this.queryFrom.dictCode,
        currentPage: this.pagination.current.toString(),
        pageSize: this.pagination.pageSize.toString()
      }
      selectSysDictList(params).then(res => {
        if (res.retCode === 0) {
          this.data = res.retObj.data
          this.pagination.total = parseInt(res.retObj.count)
        }
        this.loading = false
      }).catch(error => {
        this.loading = false
        console.log(error)
      })
    },
    onChangeZd (pagination) {
      this.zdPagination = pagination
      this.onZdQuery()
    },
    onZdQuery () {
      this.zdLoading = true
      const params = {
        spName: this.queryZdFrom.spName === '' ? null : this.queryZdFrom.spName,
        spState: this.queryZdFrom.spState === 'null' ? null : this.queryZdFrom.spState,
        spType: this.queryZdFrom.spType === '' ? null : this.queryZdFrom.spType,
        currentPage: this.zdPagination.current.toString(),
        pageSize: this.zdPagination.pageSize.toString()
      }
      selectSysDictParamList(params).then(res => {
        if (res.retCode === 0) {
          this.zdData = res.retObj.data
          this.zdPagination.total = parseInt(res.retObj.count)
        }
      }).catch(error => {
        console.log(error)
      }).finally(() => {
        this.zdLoading = false
      })
    },
    showModal () {
      this.addVisible = true
      this.title = '新增字典'
      this.flag = true
      getDictMaxCode().then(res => {
        this.addForm = {
          dictId: '',
          dictName: '',
          dictCode: res.retObj.maxCode + '',
          bz: ''
        }
      })
    },
    zdShowModal () {
      this.zdVisible = true
      this.title = '新增数据项'
      this.flag = true
      this.zdForm = {
        spValue: '',
        spType: this.queryZdFrom.spType,
        spName: '',
        spState: true,
        spWeight: '',
        spRemark: ''
      }
    },
    updateShowModal (text, record) {
      this.addVisible = true
      this.title = '编辑字典'
      this.flag = false
      this.addForm = {
        dictId: record.dictId,
        dictName: record.dictName,
        dictCode: record.dictCode,
        bz: record.bz
      }
    },
    updateZdShowModal (text, record) {
      this.zdVisible = true
      this.title = '编辑字典'
      this.flag = false
      this.zdForm = {
        spId: record.spId,
        spValue: record.spValue,
        spType: record.spType,
        spName: record.spName,
        spState: record.spState === '1',
        spWeight: record.spWeight === '' || record.spWeight === null ? 0 : parseInt(record.spWeight),
        spRemark: record.spRemark
      }
    },
    confirmDel (text, record) {
      deleteSysDict({ 'dictId': record.dictId }).then(res => {
        if (res.retCode === 0) {
          this.$notification['success']({
            message: '提示',
            description: '删除成功！',
            duration: 8
          })
          this.onQuery()
        } else {
          this.$notification['error']({
            message: '提示',
            description: res.retMsg,
            duration: 8
          })
        }
      })
    },
    confirmZdDel (text, record) {
      deleteSysDictParam({ 'spId': record.spId }).then(res => {
        if (res.retCode === 0) {
          this.$notification['success']({
            message: '提示',
            description: '删除成功！',
            duration: 8
          })
          this.onZdQuery()
        } else {
          this.$notification['error']({
            message: '提示',
            description: res.retMsg,
            duration: 8
          })
        }
      })
    },
    onSave () {
      this.$refs.ruleAddForm.validate(valid => {
        if (valid) {
          const params = {
            dictName: this.addForm.dictName,
            dictCode: this.addForm.dictCode,
            bz: this.addForm.bz
          }
          saveDictInfo(params).then(res => {
            if (res.retCode === 0) {
              this.$notification['success']({
                message: '提示',
                description: '字典信息保存成功！',
                duration: 8
              })
              this.onQuery()
              this.addForm = {
                dictId: '',
                dictName: '',
                dictCode: '',
                bz: ''
              }
              this.addVisible = false
            } else {
              this.$notification['error']({
                message: '提示',
                description: res.retMsg,
                duration: 8
              })
            }
          })
        } else {
          return false
        }
      })
    },
    onZdSave () {
      this.$refs.ruleZdForm.validate(valid => {
        if (valid) {
          const params = {
            spValue: this.zdForm.spValue === '' ? null : this.zdForm.spValue,
            spType: this.zdForm.spType === '' ? null : this.zdForm.spType,
            spName: this.zdForm.spName === '' ? null : this.zdForm.spName,
            spState: this.zdForm.spState ? '1' : '0',
            spWeight: this.zdForm.spWeight === '' ? null : this.zdForm.spWeight,
            spRemark: this.zdForm.spRemark === '' ? null : this.zdForm.spRemark
          }
          saveDictParamInfo(params).then(res => {
            if (res.retCode === 0) {
              this.$notification['success']({
                message: '提示',
                description: '参数信息保存成功！',
                duration: 8
              })
              this.onZdQuery()
              this.zdForm = {
                spValue: '',
                spType: '',
                spName: '',
                spState: true,
                spWeight: '',
                spRemark: ''
              }
              this.zdVisible = false
            } else {
              this.$notification['error']({
                message: '提示',
                description: res.retMsg,
                duration: 8
              })
            }
          })
        } else {
          return false
        }
      })
    },
    handleChangeGender (value) {
      this.queryZdFrom.spState = value
    },
    onUpdate () {
      this.$refs.ruleAddForm.validate(valid => {
        if (valid) {
          const params = {
            dictId: this.addForm.dictId,
            dictName: this.addForm.dictName,
            dictCode: this.addForm.dictCode,
            bz: this.addForm.bz
          }
          updateSysDict(params).then(res => {
            if (res.retCode === 0) {
              this.$notification['success']({
                message: '提示',
                description: '字典信息修改成功！',
                duration: 8
              })
              this.onQuery()
              this.addVisible = false
            } else {
              this.$notification['error']({
                message: '提示',
                description: res.retMsg,
                duration: 8
              })
            }
          })
        } else {
          return false
        }
      })
    },
    onZdUpdate () {
      this.$refs.ruleZdForm.validate(valid => {
        if (valid) {
          const params = {
            spId: this.zdForm.spId,
            spValue: this.zdForm.spValue === '' ? null : this.zdForm.spValue,
            spType: this.zdForm.spType === '' ? null : this.zdForm.spType,
            spName: this.zdForm.spName === '' ? null : this.zdForm.spName,
            spState: this.zdForm.spState ? '1' : '0',
            spWeight: this.zdForm.spWeight === '' ? null : this.zdForm.spWeight,
            spRemark: this.zdForm.spRemark === '' ? null : this.zdForm.spRemark
          }
          updateSysDictParam(params).then(res => {
            if (res.retCode === 0) {
              this.$notification['success']({
                message: '提示',
                description: '字典信息修改成功！',
                duration: 8
              })
              this.onZdQuery()
              this.zdVisible = false
            } else {
              this.$notification['error']({
                message: '提示',
                description: res.retMsg,
                duration: 8
              })
            }
          })
        } else {
          return false
        }
      })
    },
    switchCheckStrictly (v) {
      if (v === 1) {
        this.checkStrictly = false
      } else if (v === 2) {
        this.checkStrictly = true
      }
    },
    expandAll () {
      this.expandedKeysss = this.allTreeKeys
    },
    closeAll () {
      this.expandedKeysss = []
    },
    checkALL () {
      this.menuIds = this.allTreeKeys
    },
    cancelCheckALL () {
      // this.checkedKeys = this.defaultCheckedKeys
      this.menuIds = []
    },
    onSelect (selectedKeys, info) {
      console.log('selected', selectedKeys, info)
    },
    handleOk () {
      console.log(this.flag)
      if (this.flag) {
        this.onSave()
      } else {
        this.onUpdate()
      }
    },
    handleZdOk () {
      console.log(this.flag)
      if (this.flag) {
        this.onZdSave()
      } else {
        this.onZdUpdate()
      }
    },
    handleZdCancel () {
      this.zdVisible = false
      this.zdForm = {
        spValue: '',
        spType: '',
        spName: '',
        spState: true,
        spWeight: '',
        spRemark: ''
      }
    },
    handleCancel () {
      this.addVisible = false
      this.addForm = {
        dictId: '',
        dictName: '',
        dictCode: '',
        bz: ''
      }
    },
    cancelDel () {
    },
    onClose () {
      this.visible = false
    },
    resetForm () {
      this.queryFrom = {
        dictName: '',
        dictCode: ''
      }
      this.initList()
    },
    resetZdForm () {
      this.queryZdFrom = {
        spType: this.queryZdFrom.spType,
        spName: '',
        spState: 'null'
      }
    }
  }
}
</script>

<style scoped lang="less">
.send-display-container {
  width: 100%;
  background-color: #ffffff;
  padding: 24px;
}

.drawer-send-display-container {
  width: 100%;
  background-color: #ffffff;
  padding: 0px;
}

.filter-container {
  display: flex;
  align-items: center;
  padding-bottom: 24px;
  justify-content: left;

  .label {
    padding-right: 20px;
    white-space: nowrap;
  }

  .input-container {
    width: 200px;
    margin-right: 20px
  }

  .btn {
    margin-right: 20px;
  }
}

.drawer-filter-container {
  display: flex;
  align-items: center;
  justify-content: left;

  .label {
    padding-right: 10px;
    white-space: nowrap;
  }

  .input-container {
    width: 200px;
    margin-right: 10px
  }

  .btn {
    margin-right: 10px;
  }
}
</style>
